# main.py
import asyncio
from logger_config import logger
from config import PROJECT_TITLE, get_env
from browser_ops import launch_browser, login, fetch_page_with_browser
from http_ops import fetch_page_with_http
from utils import extract_gender_position
import os


async def test_browser_page(browser):
    """测试需要JS分析的页面"""
    test_url = "http://172.18.0.17/general/ipanel/user/user_info.php?&USER_ID=1236"
    logger.info(f"法1:测试JS解析页面: {test_url}")

    content = await fetch_page_with_browser(browser, test_url)
    if content:
        # 保存html
        with open("browser_content.html", "w", encoding="utf-8") as f:
            f.write(content)

        extracted_by_js = extract_gender_position(content)
        logger.info(extracted_by_js)
    else:
        logger.error("JS匹配失败")


async def test_http_page():
    """测试不需要JS分析的页面"""
    test_url = "http://172.18.0.17/general/ipanel/user/user_info.php?&USER_ID=1236"
    logger.info(f"法2:测试HTTP获取页面: {test_url}")

    content = await fetch_page_with_http(test_url)
    if content:
        # 保存html
        with open("http_content.html", "w", encoding="utf-8") as f:
            f.write(content)

        extracted_by_js = extract_gender_position(content)
        logger.info(extracted_by_js)
    else:
        logger.error("JS匹配失败")



async def main():
    """主函数，协调各模块工作"""
    logger.success(PROJECT_TITLE)
    logger.info("网站测试程序启动")

    # 初始化浏览器
    browser = None
    try:
        browser = await launch_browser()

        # 登录系统
        await login(browser)
        await asyncio.sleep(2)

        # 执行测试
        if get_env('RUN_TESTS') == 'True':
            logger.info("开始执行测试用例...")
            await test_browser_page(browser)
            await test_http_page()
            logger.info("测试用例执行完成")

        logger.info("程序执行完成")
    except Exception as e:
        logger.error(f"程序运行出错: {str(e)}")
    finally:
        if browser:
            await browser.close()
            logger.info("浏览器已关闭")


if __name__ == '__main__':
    asyncio.run(main())